package servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import webservices.helper.Helper;
import control.ControlService;

/**
 * Servlet implementation class CourseManageServlet
 */
public class SlideManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SlideManageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response){
		try{
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e){}
		String requestXML = "";
		try {
			List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
			for (FileItem item : items) {
	            if (item.isFormField()) {
	                if ("action".equals(item.getFieldName())){
	                	requestXML += Helper.paramStr("action", item.getString());
	                }else if ("courseID".equals(item.getFieldName())){
	                	requestXML += Helper.paramStr("courseID", item.getString());
	                }else if ("slideName".equals(item.getFieldName())){
	                	requestXML += Helper.paramStr("slideName", Helper.decodeUtf8(item.getString()));
	                }else if ("description".equals(item.getFieldName())){
	                	requestXML += Helper.paramStr("description", Helper.decodeUtf8(item.getString()));
	                }else if ("slideID".equals(item.getFieldName())){
	                	requestXML += Helper.paramStr("slideID", item.getString());
	                }
	            } else {
	                String fileName = FilenameUtils.getName(item.getName());
	                InputStream is = item.getInputStream();
	                String link = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
	                File dir = new File(getServletContext().getRealPath("/") + "slides/");
	                if (!dir.exists()){
	                	dir.mkdir();
	                }
	                File file = new File(getServletContext().getRealPath("/") + "slides/" + link);
	                if (!file.exists()){
	                	file.createNewFile();
	                }
	                item.write(file);
	                
	                requestXML += Helper.paramStr("link", link);
	            }
	        }
			
		} catch (FileUploadException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String userID = (String)request.getSession().getAttribute("userID");
		requestXML += Helper.paramStr("userID", userID == null ? "1" : userID); 
		
		String responseXML = new ControlService().Call("SlideManage", requestXML);
		
		try {
			NodeList responseList = Helper.getResponse(responseXML);
			
			String status = ((Element)responseList.item(0)).getAttribute("name");
			
			if ("fail".equals(status)){
				response.getWriter().write("{status: -1, error:'" + ((Element)responseList.item(0)).getAttribute("value")+"'}");
			}else{
				response.getWriter().write("{status: 0}");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
